package xuegao.study.mall.oauth2.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import xuegao.study.mall.common.constant.AuthConstant;
import xuegao.study.mall.common.domain.UserDto;
import xuegao.study.mall.oauth2.domain.SecurityUser;
import xuegao.study.mall.oauth2.feign.UmsAdminService;
import xuegao.study.mall.oauth2.feign.UmsMemberService;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户管理业务类
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UmsAdminService adminService;

    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = request.getParameter("client_id");
        UserDto userDto;
        if (AuthConstant.ADMIN_CLIENT_ID.equals(clientId)) {
            userDto = adminService.loadUserByUsername(username);
        } else if (AuthConstant.PORTAL_CLIENT_ID.equals(clientId)){
            userDto = memberService.loadUserByUsername(username);
        } else {
            // 默认没有clientId,从后台查询
            userDto = adminService.loadUserByUsername(username);
        }
        if (userDto == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        userDto.setClientId(clientId);
        SecurityUser securityUser = new SecurityUser(userDto);
        if (!securityUser.isEnabled()) {
            throw new DisabledException("该账户被禁用,联系管理员");
        }
        return securityUser;
    }
}
